<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('供应商发货跟踪列表')" />
</head>
<body class="gray-bg">
     <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="formId">
                    <div class="select-list">
                        <ul>
                            <li hidden>
                                <label>项目号：</label>
                                <input type="text" name="projectNo" readonly/>
                            </li>
                            <li>
                                <label>项目负责人：</label>
                                <input type="text" name="projectManager"/>
                            </li>
                            <li>
                                <label>供应商：</label>
                                <input type="text" name="supplier"/>
                            </li>
                            <li>
                                <label>产品型号：</label>
                                <input type="text" name="productModel"/>
                            </li>
                            <li>
                                <label>预计到货时间：</label>
                                <input type="text" name="expectedArrivalDate"/>
                            </li>
                            <li>
                                <label>实际到货时间：</label>
                                <input type="text" name="actualArrivalDate"/>
                            </li>
                            <li>
                                <label>发货物流：</label>
                                <input type="text" name="logisticsTrackingNo"/>
                            </li>
                            <li>
                                <label>更新时间：</label>
                                <input type="text" class="time-input" placeholder="请选择更新时间" name="updatedAt"/>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="ds:track:add">
                    <i class="fa fa-plus"></i> 添加
                </a>
                <a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="ds:track:edit">
                    <i class="fa fa-edit"></i> 修改
                </a>
                <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="ds:track:remove">
                    <i class="fa fa-remove"></i> 删除
                </a>
                <a class="btn btn-warning" onclick="showExportOptions()" shiro:hasPermission="ds:track:export">
                    <i class="fa fa-download"></i> 导出
                </a>
                <a class="btn btn-info" onclick="importExcel()" shiro:hasPermission="ds:track:import">
                    <i class="fa fa-upload"></i> 导入
                </a>
                <a class="btn btn-info" onclick="importImages()" shiro:hasPermission="ds:track:import">
                    <i class="fa fa-image"></i> 导入图片
                </a>
            </div>
            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>

    <!-- 导入对话框 -->
    <div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="importModalLabel">导入供应商发货跟踪</h4>
                </div>
                <div class="modal-body">
                    <form id="importForm" name="importForm" class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">选择文件：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <input type="text" id="fileNameDisplay" class="form-control" readonly>
                                    <span class="input-group-btn">
                                        <button class="btn btn-primary" type="button" onclick="$('#file').click()">
                                            <i class="fa fa-folder-open"></i> 浏览文件
                                        </button>
                                    </span>
                                </div>
                                <input type="file" id="file" name="file" style="display: none" accept=".xls,.xlsx" onchange="updateFileName(this)"/>
                                <div id="fileInfo" class="help-block m-b-none" style="display: none">
                                    <i class="fa fa-file-excel-o"></i> <span id="selectedFileName"></span>
                                </div>
                                <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 仅允许导入"xls"或"xlsx"格式文件。</span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label"></label>
                            <div class="col-sm-10">
                                <a onclick="$.table.importTemplate()" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> 下载模板</a>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="submitImportForm()">导入</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div class="modal fade" id="imagePreviewModal" tabindex="-1" role="dialog" aria-labelledby="imagePreviewModalLabel">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="imagePreviewModalLabel">图片预览</h4>
                </div>
                <div class="modal-body text-center" style="position:relative;">
                    <img id="previewImage" src="" style="max-width: 100%; max-height: 600px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                    <div class="preview-controls" style="position: absolute; top: 50%; width: 100%; left: 0; transform: translateY(-50%); display: flex; justify-content: space-between; padding: 0 15px;">
                        <button id="prevImage" class="btn btn-default" style="opacity: 0.7;"><i class="fa fa-chevron-left"></i></button>
                        <button id="nextImage" class="btn btn-default" style="opacity: 0.7;"><i class="fa fa-chevron-right"></i></button>
                    </div>
                    <div class="preview-info" style="margin-top: 15px;">
                        <span id="imageCounter" style="color: #666;">图片 <span id="currentImageIndex">1</span> / <span id="totalImages">1</span></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片上传模态框 -->
    <div class="modal fade" id="uploadImageModal" tabindex="-1" role="dialog" aria-labelledby="uploadImageModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="uploadImageModalLabel">上传图片</h4>
                </div>
                <div class="modal-body">
                    <form id="uploadImageForm" enctype="multipart/form-data">
                        <input type="hidden" id="trackId" name="trackId">
                        <input type="hidden" id="imageType" name="imageType">
                        <div class="form-group">
                            <input id="imageFile" name="file" type="file" class="file-loading" multiple>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 导入图片模态框 -->
    <div class="modal fade" id="importImagesModal" tabindex="-1" role="dialog" aria-labelledby="importImagesModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="importImagesModalLabel">导入图片</h4>
                </div>
                <div class="modal-body">
                    <form id="importImagesForm" name="importImagesForm" class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">选择文件夹：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <input type="text" id="folderPathDisplay" class="form-control" readonly>
                                    <span class="input-group-btn">
                                        <button class="btn btn-primary" type="button" onclick="$('#folderInput').click()">
                                            <i class="fa fa-folder-open"></i> 浏览文件夹
                                        </button>
                                    </span>
                                </div>
                                <input type="file" id="folderInput" webkitdirectory directory multiple style="display: none" accept="image/*" onchange="handleFolderSelection(this)"/>
                                <div id="folderInfo" class="help-block m-b-none" style="display: none">
                                    <i class="fa fa-folder"></i> <span id="selectedFolderName"></span>
                                </div>
                                <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 请选择包含图片的文件夹，图片命名格式：项目号_产品号_类型.jpg</span>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="submitImportImages()">导入</button>
                </div>
            </div>
        </div>
    </div>

     <!-- 导出选项模态框 -->
     <div class="modal fade" id="exportOptionsModal" tabindex="-1" role="dialog" aria-labelledby="exportOptionsModalLabel">
         <div class="modal-dialog" role="document">
             <div class="modal-content">
                 <div class="modal-header">
                     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                     <h4 class="modal-title" id="exportOptionsModalLabel">导出选项</h4>
                 </div>
                 <div class="modal-body">
                     <form id="exportOptionsForm">
                         <div class="form-group">
                             <label class="checkbox-inline">
                                 <input type="checkbox" id="exportImages" name="exportImages" value="1"> 导出图片（如果选择导出图片，导出时间会很长！）
                             </label>
                         </div>
                     </form>
                 </div>
                 <div class="modal-footer">
                     <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                     <button type="button" class="btn btn-primary" onclick="confirmExport()">确认导出</button>
                 </div>
             </div>
         </div>
     </div>

    <th:block th:include="include :: footer" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <script th:inline="javascript">
        var editFlag = [[${@permission.hasPermi('ds:track:edit')}]];
        var removeFlag = [[${@permission.hasPermi('ds:track:remove')}]];
        var supplierPhotoStatusDatas = [[${@dict.getType('sys_yes_no')}]];
        var prefix = ctx + "ds/track";
        
        // 获取URL参数
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURIComponent(r[2]); return null;
        }

        $(function() {
            // 获取URL中的项目号参数
            var projectNo = getUrlParam('projectNo');
            if (projectNo) {
                // 设置项目号输入框的值
                $('input[name="projectNo"]').val(projectNo);

                var productModel = getUrlParam('productModel');
                $('input[name="productModel"]').val(productModel);


                // 自动触发搜索
                $.table.search();
            }

            var options = {
                url: prefix + "/list",
                createUrl: prefix + "/add/"+encodeURIComponent(projectNo),
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
                importTemplateUrl: prefix + "/importTemplate",
                modalName: "供应商发货跟踪",
                striped: true,
                bordered: true,
                fixedColumns: true,
                fixedNumber: 2,
                pagination: true,
                pageSize: 100,
                clickToSelect: true,
                singleSelect: false,
                uniqueId: "id",
                showToggle: false,
                cardView: false,
                height: 650,
                stickyHeader: true,
                stickyHeaderOffsetY: 0,
                sortable: true,  // 启用排序功能
                sortName: "expectedArrivalDate",
                sortOrder: "desc", // 默认排序方式
                rowStyle: function(row, index) {
                    return {
                        classes: 'table-row'
                    };
                },
                columns: [{
                    checkbox: true,
                    width: 40
                },
                {
                    field: 'id',
                    title: 'ID',
                    visible: true,
                    sortable: true
                },
                {
                    field: 'projectNo',
                    title: '项目号',
                    align: 'center',
                    width: 100
                },
                {
                    field: 'projectManager',
                    title: '项目负责人',
                    align: 'center',
                    width: 100
                },
                {
                    field: 'supplier',
                    title: '供应商',
                    align: 'center',
                    width: 120
                },
                {
                    field: 'productCode',
                    title: '产品号'
                },
                {
                    field: 'productModel',
                    title: '产品型号',
                    width: 140
                },
                {
                    field: 'productNum',
                    title: '数量'
                },
                {
                    field: 'currency',
                    title: '币种'
                },
                {
                    field: 'placeShipment',
                    title: '发货地'
                },
                {
                    field: 'expectedArrivalDate',
                    title: '预计到货时间',
                    sortable: true
                },
                {
                    field: 'actualArrivalDate',
                    title: '实际到货时间',
                    sortable: true,  // 启用排序
                    align: 'center'
                },
                // {
                //     field: 'shippingDocPhoto',
                //     title: '供应商提供货物照片',
                //     width: 130,
                //     formatter: function(value, row, index) {
                //         var html = '<div class="photo-container" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;max-width:120px;margin:0 auto;">';
                //         if (value) {
                //             var photos = value.split(',');
                //             var displayCount = 0;
                //             for (var i = 0; i < photos.length; i++) {
                //                 var photo = photos[i];
                //                 if (photo) {
                //                     // 每两个图片一行
                //                     if (displayCount % 2 === 0 && displayCount > 0) {
                //                         html += '<div style="flex-basis:100%;height:4px;"></div>'; // 换行，增加行间距
                //                     }
                //                     html += '<div class="photo-item" style="position:relative;border:1px solid #ddd;border-radius:3px;padding:1px;flex:0 0 calc(50% - 2px);">';
                //                     html += '<a href="javascript:void(0)" onclick="previewImage(\'' + photo + '\', [\'' + photos.join('\',\'') + '\'])">';
                //                     html += '<img src="' + photo + '"  loading="lazy" style="width:46px;height:46px;object-fit:cover;display:block;border-radius:2px;"/>';
                //                     html += '</a>';
                //                     html += '<button class="btn btn-danger btn-xs" style="position:absolute;top:-5px;right:-5px;border-radius:50%;padding:0 4px;z-index:10;font-size:10px;" onclick="deletePhoto(' + row.id + ', \'shippingDocPhoto\', ' + i + ')">×</button>';
                //                     html += '</div>';
                //                     displayCount++;
                //                 }
                //             }
                //         }
                //         html += '<div style="margin-top:6px;width:100%;text-align:center;">';
                //         html += '<button class="btn btn-primary btn-xs" style="padding:2px 6px;" onclick="uploadImage(\'shippingDocPhoto\', ' + row.id + ')"><i class="fa fa-upload"></i></button>';
                //         html += '</div>';
                //         html += '</div>';
                //         return html;
                //     }
                // },
                // {
                //     field: 'supplierPackingList',
                //     title: '供应商提供箱单',
                //     align: 'center',
                //     width: 130,
                //     formatter: function(value, row, index) {
                //         var html = '<div class="photo-container" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;max-width:120px;margin:0 auto;">';
                //         if (value) {
                //             var photos = value.split(',');
                //             var displayCount = 0;
                //             for (var i = 0; i < photos.length; i++) {
                //                 var photo = photos[i];
                //                 if (photo) {
                //                     // 每两个图片一行
                //                     if (displayCount % 2 === 0 && displayCount > 0) {
                //                         html += '<div style="flex-basis:100%;height:4px;"></div>'; // 换行，增加行间距
                //                     }
                //                     html += '<div class="photo-item" style="position:relative;border:1px solid #ddd;border-radius:3px;padding:1px;flex:0 0 calc(50% - 2px);">';
                //                     html += '<a href="javascript:void(0)" onclick="previewImage(\'' + photo + '\', [\'' + photos.join('\',\'') + '\'])">';
                //                     html += '<img src="' + photo + '"  loading="lazy" style="width:46px;height:46px;object-fit:cover;display:block;border-radius:2px;"/>';
                //                     html += '</a>';
                //                     html += '<button class="btn btn-danger btn-xs" style="position:absolute;top:-5px;right:-5px;border-radius:50%;padding:0 4px;z-index:10;font-size:10px;" onclick="deletePhoto(' + row.id + ', \'supplierPackingList\', ' + i + ')">×</button>';
                //                     html += '</div>';
                //                     displayCount++;
                //                 }
                //             }
                //         }
                //         html += '<div style="margin-top:6px;width:100%;text-align:center;">';
                //         html += '<button class="btn btn-primary btn-xs" style="padding:2px 6px;" onclick="uploadImage(\'supplierPackingList\', ' + row.id + ')"><i class="fa fa-upload"></i></button>';
                //         html += '</div>';
                //         html += '</div>';
                //         return html;
                //     }
                // },
                // {
                //     field: 'supplierLogistics',
                //     title: '供应商物流',
                //     align: 'center',
                //     width: 110
                // },
                {
                    field: 'supplierPhotoUrl',
                    title: '跟单验货照片',
                    width: 130,
                    formatter: function(value, row, index) {
                        var html = '<div class="photo-container" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;max-width:120px;margin:0 auto;">';
                        if (value) {
                            var photos = value.split(',');
                            var displayCount = 0;
                            for (var i = 0; i < photos.length; i++) {
                                var photo = photos[i];
                                if (photo) {
                                    // 每两个图片一行
                                    if (displayCount % 2 === 0 && displayCount > 0) {
                                        html += '<div style="flex-basis:100%;height:4px;"></div>'; // 换行，增加行间距
                                    }
                                    html += '<div class="photo-item" style="position:relative;border:1px solid #ddd;border-radius:3px;padding:1px;flex:0 0 calc(50% - 2px);">';
                                    html += '<a href="javascript:void(0)" onclick="previewImage(\'' + photo + '\', [\'' + photos.join('\',\'') + '\'])">';
                                    html += '<img src="' + photo + '"  loading="lazy" style="width:46px;height:46px;object-fit:cover;display:block;border-radius:2px;"/>';
                                    html += '</a>';
                                    html += '<button class="btn btn-danger btn-xs" style="position:absolute;top:-5px;right:-5px;border-radius:50%;padding:0 4px;z-index:10;font-size:10px;" onclick="deletePhoto(' + row.id + ', \'supplierPhotoUrl\', ' + i + ')">×</button>';
                                    html += '</div>';
                                    displayCount++;
                                }
                            }
                        }
                        html += '<div style="margin-top:6px;width:100%;text-align:center;">';
                        html += '<button class="btn btn-primary btn-xs" style="padding:2px 6px;" onclick="uploadImage(\'supplierPhotoUrl\', ' + row.id + ')"><i class="fa fa-upload"></i></button>';
                        html += '</div>';
                        html += '</div>';
                        return html;
                    }
                },
                {
                    field: 'logisticsTrackingNo',
                    title: '发货单号',
                    align: 'center',
                    width: 110,
                    sortable: true  // 启用排序
                },
                // {
                //     field: 'supplierPackingListUrl',
                //     title: '跟单验货箱单',
                //     width: 130,
                //     formatter: function(value, row, index) {
                //         var html = '<div class="photo-container" style="display:flex;flex-wrap:wrap;gap:4px;align-items:center;max-width:120px;margin:0 auto;">';
                //         if (value) {
                //             var photos = value.split(',');
                //             var displayCount = 0;
                //             for (var i = 0; i < photos.length; i++) {
                //                 var photo = photos[i];
                //                 if (photo) {
                //                     // 每两个图片一行
                //                     if (displayCount % 2 === 0 && displayCount > 0) {
                //                         html += '<div style="flex-basis:100%;height:4px;"></div>'; // 换行，增加行间距
                //                     }
                //                     html += '<div class="photo-item" style="position:relative;border:1px solid #ddd;border-radius:3px;padding:1px;flex:0 0 calc(50% - 2px);">';
                //                     html += '<a href="javascript:void(0)" onclick="previewImage(\'' + photo + '\', [\'' + photos.join('\',\'') + '\'])">';
                //                     html += '<img src="' + photo + '" loading="lazy" style="width:46px;height:46px;object-fit:cover;display:block;border-radius:2px;"/>';
                //                     html += '</a>';
                //                     html += '<button class="btn btn-danger btn-xs" style="position:absolute;top:-5px;right:-5px;border-radius:50%;padding:0 4px;z-index:10;font-size:10px;" onclick="deletePhoto(' + row.id + ', \'supplierPackingListUrl\', ' + i + ')">×</button>';
                //                     html += '</div>';
                //                     displayCount++;
                //                 }
                //             }
                //         }
                //         html += '<div style="margin-top:6px;width:100%;text-align:center;">';
                //         html += '<button class="btn btn-primary btn-xs" style="padding:2px 6px;" onclick="uploadImage(\'supplierPackingListUrl\', ' + row.id + ')"><i class="fa fa-upload"></i></button>';
                //         html += '</div>';
                //         html += '</div>';
                //         return html;
                //     }
                // },
                {
                    field: 'warehouse',
                    title: '发货仓库',
                    sortable: true
                },
                {
                    field: 'shippedQuantity',
                    title: '发货数量',
                    sortable: true
                },
                {
                    field: 'remarks',
                    title: '备注',
                    align: 'center',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'createdAt',
                    title: '创建时间',
                    align: 'center',
                    width: 120
                },
                {
                    field: 'updatedAt',
                    title: '更新时间',
                    align: 'center',
                    width: 120
                },
                {
                    title: '操作',
                    align: 'center',
                    width: 80,
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<div style="margin-bottom:5px;"><a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i></a></div>');
                        actions.push('<div><a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-trash"></i></a></div>');
                        return actions.join('');
                    }
                }]
            };
            $.table.init(options);
            
            // 添加自定义CSS样式
            $("<style>")
                .prop("type", "text/css")
                .html(`
                    .table-row td {
                        vertical-align: middle !important;
                        padding: 8px 5px !important;
                    }
                    .fixed-table-container thead th .th-inner {
                        padding: 8px 5px;
                    }
                    .btn-xs {
                        padding: 1px 5px;
                    }
                    .btn-group-sm>.btn, .btn-sm {
                        padding: 3px 8px;
                    }
                `)
                .appendTo("head");
        });

        // 导入Excel按钮点击事件
        function importExcel() {
            // 重置表单
            $('#importForm')[0].reset();
            $('#fileInfo').hide();
            // 显示导入对话框
            $('#importModal').modal('show');
        }

        // 导入Excel
        function submitImportForm() {
            var formData = new FormData();
            var fileInput = document.getElementById("file");
            
            if (fileInput.files.length === 0) {
                $.modal.alertWarning("请先选择要导入的Excel文件！");
                return;
            }
            
            // 验证文件格式
            var fileName = fileInput.files[0].name;
            var fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            if (fileExt != ".xls" && fileExt != ".xlsx") {
                $.modal.alertWarning("文件格式不正确，请选择 .xls 或 .xlsx 格式的文件！");
                return;
            }
            
            formData.append("file", fileInput.files[0]);
            $.modal.loading("正在导入数据，请稍候...");
            
            $.ajax({
                url: prefix + "/importData",
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $('#importModal').modal('hide'); // 先关闭导入对话框
                        $.modal.closeLoading(); // 关闭加载提示
                        $.modal.alertSuccess(result.msg); // 显示成功提示
                        $.table.refresh(); // 刷新表格数据
                    } else {
                        $.modal.closeLoading();
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.closeLoading();
                    $.modal.alertError("导入失败，请联系系统管理员");
                }
            });
        }

        // 更新文件名显示
        function updateFileName(input) {
            var fileName = input.value;
            if (fileName) {
                fileName = fileName.split('\\').pop();
                $('#fileNameDisplay').val(fileName);
                $('#selectedFileName').text(fileName);
                $('#fileInfo').show();
            } else {
                $('#fileNameDisplay').val('');
                $('#fileInfo').hide();
            }
        }

        // 图片预览函数
        function previewImage(url, images) {
            var currentImages = images || [url];
            var currentIndex = 0;
            
            // 当只传入单个URL而没有传入images数组时
            if (!images && url) {
                currentIndex = 0;
            } else if (images) {
                // 如果传入了images数组，找到当前url在数组中的索引
                currentIndex = currentImages.indexOf(url);
                if (currentIndex === -1) currentIndex = 0;
            }
            
            // 更新图片和计数器
            function updatePreview() {
                $('#previewImage').attr('src', currentImages[currentIndex]);
                $('#currentImageIndex').text(currentIndex + 1);
                $('#totalImages').text(currentImages.length);
                
                // 更新导航按钮状态
                if (currentImages.length <= 1) {
                    $('#prevImage, #nextImage').hide();
                    $('#imageCounter').hide();
                } else {
                    $('#prevImage, #nextImage').show();
                    $('#imageCounter').show();
                }
            }
            
            // 初始化
            updatePreview();
            
            // 绑定导航按钮事件
            $('#prevImage').off('click').on('click', function() {
                if (currentIndex > 0) {
                    currentIndex--;
                    updatePreview();
                }
            });
            
            $('#nextImage').off('click').on('click', function() {
                if (currentIndex < currentImages.length - 1) {
                    currentIndex++;
                    updatePreview();
                }
            });
            
            // 显示模态框
            $('#imagePreviewModal').modal('show');
        }

        // 保存上传的图片URL
        var uploadedImageUrls = [];
        // 上传图片
        function uploadImage(type, trackId) {
            $('#trackId').val(trackId);
            $('#imageType').val(type);

            // 清空已上传图片URL数组
            uploadedImageUrls = [];

            // 销毁之前的实例
            if ($("#imageFile").data('fileinput')) {
                $("#imageFile").fileinput('destroy');
            }
            
            // 初始化文件上传控件
            $("#imageFile").fileinput({
                theme: 'fa',
                language: 'zh',
                uploadUrl: ctx + 'common/upload',
                uploadAsync: true,
                showCaption: true,
                showUpload: true,
                showRemove: true,
                showPreview: true,
                showCancel: false,
                showClose: false,
                maxFileCount: 10,
                maxFileSize: 5120, // 5MB
                allowedFileTypes: ['image'],
                allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif'],
                uploadExtraData: function() {
                    return {
                        trackId: $('#trackId').val(),
                        type: $('#imageType').val()
                    };
                },
                layoutTemplates: {
                    actionUpload: '',  // 不显示上传按钮
                    actionZoom: ''     // 不显示预览按钮
                },
                initialPreviewAsData: true,
                dropZoneEnabled: true,
                browseLabel: '选择图片',
                msgPlaceholder: '请选择图片...',
                browseClass: 'btn btn-primary',
                browseIcon: '<i class="fa fa-folder-open"></i>&nbsp;',
                removeLabel: '清除',
                removeIcon: '<i class="fa fa-trash"></i>',
                removeTitle: '清除选中文件',
                elErrorContainer: '#kv-error-2'
            }).on('filebatchselected', function(event, files) {
                // 选择文件后自动上传
                $(this).fileinput('upload');
            }).on('fileuploaded', function(event, data, previewId, index) {
                if (data.response.code == web_status.SUCCESS) {
                    // 上传成功后，获取当前记录，并追加新图片URL
                    var trackId = $('#trackId').val();
                    var type = $('#imageType').val();
                    var imageUrl = data.response.url;  // 假设返回的URL在response.url中
                    // 从response中获取所有成功上传的图片URL
                    if (imageUrl) {
                        uploadedImageUrls.push(data.response.url);
                    }
                } else {
                    $.modal.alertError(data.response.msg);
                }
            }).on('filebatchuploadcomplete', function(event, files, extra) {
                // 所有文件上传完成后，更新记录
                if (uploadedImageUrls.length > 0) {
                    updateTrackWithImages(uploadedImageUrls);
                } else {
                    $.modal.alertWarning("未获取到上传的图片URL");
                }
            }).on('fileerror', function(event, data, msg) {
                $.modal.alertError("上传失败：" + msg);
            });
            
            $('#uploadImageModal').modal('show');
        }

        // 更新记录图片函数
        function updateTrackWithImages(imageUrls) {
            var trackId = $('#trackId').val();
            var type = $('#imageType').val();

            // 获取当前记录
            $.ajax({
                url: prefix + "/find/" + trackId,
                type: 'GET',
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        var track = result.data;
                        var currentUrls = '';

                        // 根据类型获取当前的URL字段
                        switch (type) {
                            case 'supplierPhotoUrl':
                                currentUrls = track.supplierPhotoUrl || '';
                                break;
                            case 'supplierPackingList':
                                currentUrls = track.supplierPackingList || '';
                                break;
                            case 'supplierPackingListUrl':
                                currentUrls = track.supplierPackingListUrl || '';
                                break;
                            case 'shippingDocPhoto':
                                currentUrls = track.shippingDocPhoto || '';
                                break;
                        }

                        // 将当前URL字符串转换为数组
                        var urlArray = currentUrls ? currentUrls.split(',').filter(Boolean) : [];

                        // 添加新URL（如果不存在）
                        for (var i = 0; i < imageUrls.length; i++) {
                            if (!urlArray.includes(imageUrls[i])) {
                                urlArray.push(imageUrls[i]);
                            }
                        }

                        // 重新组合URL字符串
                        var newUrls = urlArray.join(',');

                        // 构造更新数据
                        var formData = {
                            'id': trackId
                        };

                        // 根据type设置不同的字段
                        switch (type) {
                            case 'supplierPhotoUrl':
                                formData.supplierPhotoUrl = newUrls;
                                break;
                            case 'supplierPackingList':
                                formData.supplierPackingList = newUrls;
                                break;
                            case 'supplierPackingListUrl':
                                formData.supplierPackingListUrl = newUrls;
                                break;
                            case 'shippingDocPhoto':
                                formData.shippingDocPhoto = newUrls;
                                break;
                        }

                        // 调用编辑接口更新记录
                        $.ajax({
                            url: prefix + "/edit",
                            type: 'POST',
                            data: formData,
                            success: function(result) {
                                if (result.code == web_status.SUCCESS) {
                                    $.modal.alertSuccess("上传成功");
                                    $.table.refresh(); // 添加表格刷新
                                    $('#uploadImageModal').modal('hide');
                                } else {
                                    $.modal.alertError(result.msg);
                                }
                            },
                            error: function() {
                                $.modal.alertError("更新失败，请联系系统管理员");
                            }
                        });
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function() {
                    $.modal.alertError("获取记录失败，请联系系统管理员");
                }
            });
        }

        // 删除照片
        function deletePhoto(trackId, type, index) {
            $.modal.confirm("确定要删除这张照片吗？", function() {
                // 获取当前记录
                $.ajax({
                    url: prefix + "/find/" + trackId,
                    type: 'GET',
                    success: function(result) {
                        if (result.code == web_status.SUCCESS) {
                            var track = result.data;
                            var urls;
                            // 根据type获取对应的URL字段
                            switch (type) {
                                case 'supplierPhotoUrl':
                                    urls = track.supplierPhotoUrl;
                                    break;
                                case 'supplierPackingList':
                                    urls = track.supplierPackingList;
                                    break;
                                case 'supplierPackingListUrl':
                                    urls = track.supplierPackingListUrl;
                                    break;
                                case 'shippingDocPhoto':
                                    urls = track.shippingDocPhoto;
                                    break;
                            }
                            
                            // 从URL列表中删除指定的URL
                            if (urls) {
                                var urlArray = urls.split(',');
                                urlArray.splice(index, 1);
                                
                                // 构造更新数据
                                var newUrlString = urlArray.join(',');
                                var formData = {
                                    'id': trackId
                                };
                                
                                // 根据type设置不同的字段
                                switch (type) {
                                    case 'supplierPhotoUrl':
                                        formData.supplierPhotoUrl = newUrlString;
                                        break;
                                    case 'supplierPackingList':
                                        formData.supplierPackingList = newUrlString;
                                        break;
                                    case 'supplierPackingListUrl':
                                        formData.supplierPackingListUrl = newUrlString;
                                        break;
                                    case 'shippingDocPhoto':
                                        formData.shippingDocPhoto = newUrlString;
                                        break;
                                }
                                
                                // 调用编辑接口更新记录
                                $.ajax({
                                    url: prefix + "/edit",
                                    type: 'POST',
                                    data: formData,
                                    success: function(result) {
                                        if (result.code == web_status.SUCCESS) {
                                            $.modal.alertSuccess("删除成功");
                                            $.table.refresh();
                                        } else {
                                            $.modal.alertError(result.msg);
                                        }
                                    },
                                    error: function() {
                                        $.modal.alertError("更新失败，请联系系统管理员");
                                    }
                                });
                            }
                        } else {
                            $.modal.alertError(result.msg);
                        }
                    },
                    error: function() {
                        $.modal.alertError("获取记录失败，请联系系统管理员");
                    }
                });
            });
        }

        // 重置表单
        function resetForm() {
            // 获取URL参数
            var projectNo = getUrlParam('projectNo');
            
            // 重置表单
            $('#formId')[0].reset();
            
            // 恢复URL参数
            if (projectNo) {
                $('input[name="projectNo"]').val(projectNo);
            }
            // 自动触发搜索
            $.table.search();
        }

        // 导入图片按钮点击事件
        function importImages() {
            // 重置表单
            $('#importImagesForm')[0].reset();
            $('#folderInfo').hide();
            // 显示导入对话框
            $('#importImagesModal').modal('show');
        }

        // 处理文件夹选择
        function handleFolderSelection(input) {
            var files = input.files;
            if (files.length > 0) {
                var folderPath = files[0].webkitRelativePath.split('/')[0];
                $('#folderPathDisplay').val(folderPath);
                $('#selectedFolderName').text(folderPath);
                $('#folderInfo').show();
            } else {
                $('#folderPathDisplay').val('');
                $('#folderInfo').hide();
            }
        }

        // 提交导入图片
        function submitImportImages() {
            var files = $('#folderInput')[0].files;
            if (files.length === 0) {
                $.modal.alertWarning("请先选择包含图片的文件夹！");
                return;
            }

            var formData = new FormData();
            var imageMap = new Map(); // 用于存储按项目号和产品号分组的图片

            // 图片类型与字段的对应关系
            var typeFieldMap = {
                '供应商提供货物照片': 'shippingDocPhoto',
                '供应商提供箱单': 'supplierPackingList',
                '跟单验货照片': 'supplierPhotoUrl',
                '跟单验货箱单': 'supplierPackingListUrl'
            };
            // 处理所有文件
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                if (file.type.startsWith('image/')) {
                    var fileName = file.name;
                    var parts = fileName.split('_');

                    if (parts.length >= 3) {
                        var projectNo = parts[0];
                        var productCode = parts[1];
                        // 获取图片类型（可能是带序号的格式）
                        var imageType = parts[2];
                        // 如果最后一部分是数字，说明是带序号的格式
                        if (parts.length > 3) {
                            imageType = parts[2];
                        } else {
                            imageType = parts[2].replace(/\.[^/.]+$/, ""); // 移除文件扩展名
                        }

                        // 检查图片类型是否有效
                        if (!typeFieldMap[imageType]) {
                            $.modal.alertWarning("图片类型无效：" + imageType + "，文件名：" + fileName);
                            continue;
                        }

                        var key = projectNo + '_' + productCode + '_' + imageType;

                        if (!imageMap.has(key)) {
                            imageMap.set(key, []);
                        }
                        imageMap.get(key).push({
                            file: file,
                            type: imageType,
                            field: typeFieldMap[imageType]
                        });
                    }
                }
            }

            if (imageMap.size === 0) {
                $.modal.alertWarning("未找到符合命名规则的图片文件！");
                return;
            }

            $.modal.loading("正在上传图片，请稍候...");

            // 处理每个项目号和产品号的组合
            var promises = [];
            imageMap.forEach(function(files, key) {
                var parts = key.split('_');
                var projectNo = parts[0];
                var productCode = parts[1];

                // 为每个文件创建上传任务
                files.forEach(function(fileInfo) {
                    var promise = new Promise(function(resolve, reject) {
                        var fileFormData = new FormData();
                        fileFormData.append('file', fileInfo.file);
                        fileFormData.append('projectNo', projectNo);
                        fileFormData.append('productCode', productCode);

                        $.ajax({
                            url: ctx + 'common/upload',
                            type: 'POST',
                            data: fileFormData,
                            async: false,
                            processData: false,
                            contentType: false,
                            success: function(result) {
                                if (result.code == web_status.SUCCESS) {
                                    // 更新对应记录的指定字段
                                    updateTrackPhoto(projectNo, productCode, result.url, fileInfo.field, resolve);
                                } else {
                                    reject(result.msg);
                                }
                            },
                            error: function() {
                                reject("上传失败");
                            }
                        });
                    });
                    promises.push(promise);
                });
            });

            // 等待所有上传完成
            Promise.all(promises)
                .then(function() {
                    $.modal.closeLoading();
                    $.modal.alertSuccess("图片导入成功");
                    $('#importImagesModal').modal('hide');
                    $.table.refresh();
                })
                .catch(function(error) {
                    $.modal.closeLoading();
                    $.modal.alertError("图片导入失败：" + error);
                });
        }

        // 更新记录的指定字段
        function updateTrackPhoto(projectNo, productCode, imageUrl, field, callback) {
            // 先查找对应的记录
            $.ajax({
                url: prefix + "/list",
                type: 'POST',
                async: false,
                data: {
                    projectNo: projectNo,
                    productCode: productCode
                },
                success: function(result) {
                    if (result.code == web_status.SUCCESS && result.rows.length > 0) {
                        var track = result.rows[0];
                        var currentPhotos = track[field] || '';
                        var photoArray = currentPhotos ? currentPhotos.split(',') : [];

                        // 添加新图片URL（如果不存在）
                        if (!photoArray.includes(imageUrl)) {
                            photoArray.push(imageUrl);
                        }

                        // 更新记录
                        var formData = {
                            'id': track.id
                        };
                        formData[field] = photoArray.join(',');

                        $.ajax({
                            url: prefix + "/edit",
                            type: 'POST',
                            data: formData,
                            async: false,
                            success: function(result) {
                                if (result.code == web_status.SUCCESS) {
                                    callback();
                                } else {
                                    callback(result.msg);
                                }
                            },
                            error: function() {
                                callback("更新记录失败");
                            }
                        });
                    } else {
                        callback("未找到对应的记录");
                    }
                },
                error: function() {
                    callback("查询记录失败");
                }
            });
        }

        // 显示导出选项
        function showExportOptions() {
            $('#exportOptionsModal').modal('show');
        }

        // 确认导出
        function confirmExport() {
            debugger
            var exportImages = $('#exportImages').is(':checked');

            // 修改exportUrl，添加参数
            table.options.exportUrl = prefix + "/export?exportImages=" + exportImages;

            // 传递表单ID
            $.table.exportExcel();

            $('#exportOptionsModal').modal('hide');
        }
    </script>
</body>
</html>